"use client"

import DeviceDetailPage from "@/components/device-detail-page"
import { useEffect, useState } from "react"

export default function ElectricalDeviceDetailPage({ 
  params, 
  searchParams 
}: {
  params: Promise<{ name: string }>
  searchParams: Promise<{ tab?: string }>
}) {
  const [deviceId, setDeviceId] = useState<number | null>(null)
  const [deviceName, setDeviceName] = useState("")
  const [defaultTab, setDefaultTab] = useState("naming")
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    (async () => {
      const resolvedParams = await params
      const resolvedSearchParams = await searchParams
      const name = decodeURIComponent(resolvedParams.name)
      setDeviceName(name)
      setDefaultTab(resolvedSearchParams.tab || "naming")
      try {
        const res = await fetch(`/api/sqlite-devices?withParameters=false`)
        const data = await res.json()
        const found = data.find((d: any) => d.设备表及材料表中的实体对象名称 === name)
        if (found && found.id) setDeviceId(found.id)
        else setError("未找到设备")
      } catch {
        setError("加载设备失败")
      } finally {
        setLoading(false)
      }
    })()
  }, [params, searchParams])

  if (loading) return <div>加载中...</div>
  if (error || !deviceId) return <div>{error || "未找到设备"}</div>

  return (
    <DeviceDetailPage
      deviceId={deviceId}
      deviceName={deviceName}
      specialtyName="电气专业"
      specialtyRoute="electrical"
      defaultTab={defaultTab}
    />
  )
} 